const query = window.location.search;
const searchObj = Qs.parse(query ? query.substring(1) : null);
console.log(searchObj);
// 当前日期
const today = moment().startOf('day');
// 当前时间
const hour = moment().hour();
// 获取当前时间描述
const getHourDes = () => {
  if (hour >= 0 && hour < 8) {
    return '凌晨';
  } else if (hour >= 8 && hour < 12){
    return '上午';
  }else if (hour >= 12 && hour < 14){
    return '中午';
  }else if (hour >= 14 && hour < 18){
    return '下午';
  }else if (hour >= 18 && hour < 24){
    return '晚上';
  }
}
// 默认文案
const getDefaultText = () => {
  return `${getHourDes()}好！琪琪`;
};
// 日期提醒
const getTodayText = () => {
  const todayStr = today.format("yyyy年MM月DD日");
  const days = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ][today.days()];
  // 天气概述
  const wl = searchObj.wl ? searchObj.wl.split("_") : [];
  const [currentWl = '', ...wl10] = wl;
  const [tomorrow] = wl10;
  const wendu = parseInt(currentWl);
  const tqzk = currentWl.replace(`${wendu}`, "");
  const isYu = wl10.every((v) => !v.includes("雨"));
  const tomorrowwendu = parseInt(tomorrow);
  const tomorrowtqzk = tomorrow.replace(`${tomorrowwendu}`, "");
  return `今天是${todayStr}，${days}。天气平均温度为${wendu}度，天气状况：${tqzk}。\n 明天气温${tomorrowwendu}度，${tomorrowtqzk}。并且，未来十天内${
    isYu ? "无" : "有"
  }雨`;
};

/**
 * 天气预报
 * 0%-20% 几乎不会降雨
 * 30% ─50% 可能会降雨
 * 60%─ 70% 很大可能会降雨
 * 80% - 100% 会降雨
 * 
 * 上午：08:00:00 - 12:00:00

中午：12:00:01 - 13:59:59

下午：14:00:00 - 18:00:00

晚上：18:00:01 - 24:00:00
 */
// 获取一天时间的平均值
const formatSearch = (searchStr) => {
  if(!searchStr) return;
  let searchArr = searchStr.split("_");
  searchArr = Array((hour || 1) - 1).fill(null).concat(searchArr);
  // 上午平均值
  const morning =
    searchArr.slice(8, 13).reduce((sum, v) => {
      const num = Number(v);
      return num + sum;
    }, 0) / 5;
  const noon =
    searchArr.slice(12, 15).reduce((sum, v) => {
      const num = Number(v);
      return num + sum;
    }, 0) / 3;
  const afternoon =
    searchArr.slice(14, 19).reduce((sum, v) => {
      const num = Number(v);
      return num + sum;
    }, 0) / 5;
  const night =
    searchArr.slice(18, 25).reduce((sum, v) => {
      const num = Number(v);
      return num + sum;
    }, 0) / 7;
  console.log(searchArr , {morning, noon, afternoon, night});
  return { morning, noon, afternoon, night };
};
const getTodayWeather = () => {
  if (!searchObj)
    return "今天天气怎么样呢？希望善变的天气不会影响你一天的好心情呦。";
  // 天气概况 最低气温提醒是否需要添加衣物  体感温度提醒是否温度适宜
  let { fs, jsgl, wd, zwx } = searchObj;
  wd = formatSearch(wd);
  fs = formatSearch(fs);
  jsgl = formatSearch(jsgl);
  zwx = formatSearch(zwx);
  // 温度
  const wdF = ({ morning, noon, afternoon, night }) => {
    if (
      morning >= 17 &&
      morning <= 24 &&
      noon >= 17 &&
      noon <= 24 &&
      afternoon >= 17 &&
      afternoon <= 24 &&
      night >= 17 &&
      night <= 24
    ) {
      return "今天气温一天都很棒。";
    } else if (afternoon < 5) {
      return "今天气温有点冷，记得多穿点衣服。";
    } else if (afternoon < 17) {
      return "今天天气微凉，记得穿外套呢。";
    } else if (
      afternoon >= 17 &&
      afternoon <= 24 &&
      (morning > 15 || night > 15)
    ) {
      return "今天气温不错呦。";
    } else if (
      afternoon >= 17 &&
      afternoon <= 24 &&
      (morning < 15 || night < 15)
    ) {
      return "今天早上和晚上的气温还是有点低，不过中午的气温不错呢。";
    } else if (night >= 17 && night <= 24 && afternoon < 30) {
      return "今天早上和晚上的气温不错，中午有点点热。";
    } else if (night >= 17 && night <= 24 && afternoon > 30) {
      return "今天早上和晚上的气温不错，中午有非常热。";
    } else if (night > 24 && afternoon > 30) {
      return "今天一天都很热。";
    } else {
      return `今天上午气温${morning}，中午气温：${noon}，下午气温：${afternoon}，晚上气温：${night}。`;
    }
  };
  // 降雨
  const jsF = ({ morning, noon, afternoon, night }) => {
    if (morning < 0.2 && noon < 0.2 && afternoon < 0.2 && night < 0.2) {
      // 无雨
      return "今天不会下雨哦，";
    } else {
      let str = "";
      if (morning <= 0.2) {
      } else if (morning < 0.4) {
        str += "早上可能会下雨";
      } else {
        str += "今天的雨";
      }


      if (noon <= 0.2) {
        if (str) {
          str += "将会在中午停下来";
        }
      } else if (noon < 0.4) {
        !str && (str += "中午可能会下雨");
      } else {
        if (str.includes('可能')) {
          str += '中午必定会下雨'
        } 
        !str && (str += "中午的雨");
      }


      if (afternoon <= 0.2) {
        if (str && !str.endsWith("停下来")) {
          str += "将会在下午停下来";
        }
      } else if (afternoon < 0.4) {
        
        !str && (str += "下午可能会下雨");
      } else {
        if (str.includes('可能') && !str.includes('必定')) {
          str += '下午必定会下雨'
        } 
        if (!str) {
          str += "下午的雨";
        } else {
          if (str.endsWith("停下来")) {
            str += "下午又下起来了";
          } else if (str.includes("的雨") || str.includes("可能") || str.includes("必定")) {
            str += "";
          } else {
          }
        }
      }


      if (night <= 0.2) {
        if (str && !str.endsWith("停下来")) {
          str += "将会在晚上停下来";
        }
      } else if (night < 0.4) {
        !str && (str += "晚上可能会下雨");
      } else {
        if (!str) {
          str += "晚上会下雨";
        } else {
          if (str.includes('可能') && !str.includes('必定')) {
            str += '晚上必定会下雨'
          } else if (str.endsWith("停下来")) {
            str += "晚上又下起来了";
          } else if (str.includes("的雨") || str.includes("可能") || str.includes("必定")) {
            str += "晚上也不会停";
          }
        }
      }
      return str ? `下雨影响好心情了吗？${str}。` : "";
    }
  };

  // 紫外线
  const zwxF = ({ morning, noon, afternoon, night }) => {
    if (morning < 2 && noon < 2 && afternoon < 2 && night < 2) {
      return "";
    } else if (noon > 3 && afternoon > 3 && morning > 3 && night > 3) {
      return "一天的紫外线都很高，不过你是男的你怕什么？";
    } else {
      return ``;
    }
  };

  // 风速

  const fsF = ({ morning, noon, afternoon, night }) => {
    // 换算单位
    morning = Number(((morning * 1000) / 3600).toFixed(2));
    noon = Number(((noon * 1000) / 3600).toFixed(2));
    afternoon = Number(((afternoon * 1000) / 3600).toFixed(2));
    night = Number(((night * 1000) / 3600).toFixed(2));
    const feng = [morning, noon, afternoon, night];
    console.log(feng);
    if (feng.every((v) => v < 3.3)) {
      return "无风";
    } else if (feng.every((v) => v < 5)) {
      return "微风";
    } else if (feng.every((v) => v < 9)) {
      return "今天有大风，注意扬尘。";
    } else if (feng.every((v) => v < 13)) {
      return "今天有强风，呆在家里吧，你可能会被刮跑。";
    } else {
      return "今天有飓风，呆在家里吧，你肯定都会被刮跑";
    }
  };
  return `${wdF(wd)}${jsF(jsgl)}${zwxF(zwx)}${fsF(fs)}`;
};
// 一共多少日子
const getTotalDay = () => {
  const diffDay = today.diff("2007-03-03", "d");
  const diffYear = today.diff('2007-03-03', "y")
  return `从呱呱落地到今天的你。已经过了${diffDay}个日日夜夜、${diffYear}个春夏秋冬。你哭过、笑过也卑微过。${diffYear}岁的你，这是最好的年纪，也是最坏的年纪。哥希望你心中坚信童话，勇敢而美好的长大！`;
};
// 纪念日
const jinianriStr = () => {
  const jinianri = [
    {
      date: "2023-05-20",
      dateType: "公历",
      dateUse: "纪念日",
      dateUser: "wife",
      des: "我们重新认识",
    },
    {
      date: "2007-02-14",
      dateType: "农历",
      dateUse: "birthday",
      dateUser: "child",
      des: "你的生日",
    },
    {
      date: "2007-11-06",
      dateType: "农历",
      dateUse: "birthday",
      dateUser: "wife",
      des: "你亲爱的妈咪生日",
    },
    {
      date: "2007-08-24",
      dateType: "农历",
      dateUse: "birthday",
      dateUser: "wife",
      des: "你可爱的老爸生日",
    },
    // {
    //   date: "1992-03-20",
    //   dateType: "农历",
    //   dateUse: "birthday",
    //   dateUser: "wife",
    //   des: "亲亲老婆生日",
    // },
    // {
    //   date: "2020-05-27",
    //   dateType: "农历",
    //   dateUse: "birthday",
    //   dateUser: "child",
    //   des: "皓雪生日",
    // },
  ];

  // 获取日子还有多少天
  const getBir = (m, d, type = "公历", dateUse = 'birthday') => {
    const year = today.year();
    // 判断今年的农历是否过去了
    let gongli = `${year}-${m}-${d}`;
    if (type !== "公历") {
      // 农历转公历
      gongli = chineseLunar.lunarToSolar(year, +m, +d);
    }
    let dd = today.diff(gongli, "d");
    if (dd > 0 && dateUse !== '纪念日') {
      // 加一年
      if (type !== "公历") {
        gongli = chineseLunar.lunarToSolar(year + 1, +m, +d);
      } else {
        gongli = `${year + 1}-${m}-${d}`;
      }
      dd = today.diff(gongli, "d");
    }
    return  dateUse !== '纪念日' ? -dd : dd;
  };

  return jinianri.reduce((sum, item, index) => {
    const { date, dateType, des, dateUse, dateUser } = item;
    const [y, m, d] = date.split("-");
    const countDate = getBir(m, d, dateType, dateUse);
    let tips = "";
    let birthdayTips = "";
    if (dateUse === "birthday" && dateUser === "child") {
      const diffD = today.diff(date, "y") + 1;
      birthdayTips = diffD + "岁";
    }
    if (countDate === 0) {
      tips = "今天是" + birthdayTips + des;
    } else {
      tips = `距离${dateUse === '纪念日' ? '' : ''}${birthdayTips}${des}${dateUse === '纪念日' ? '已经过了' : '还有'}${countDate}天。${dateUse === '纪念日' ? '' : ''}`;
    }
    return sum + tips + (index === jinianri.length - 1 ? "" : "\n");
  }, "").split('\n').sort((a, b) => {
    const numA = a.match(/\d+/g) || [0];
    const numB = b.match(/\d+/g) || [0];
    return numA[numA.length - 1] - numB[numB.length -1]
  }).join('\n');
};

// 获取最近节假日信息
// const getHoliday = () => {
//   // https://timor.tech/api/holiday/next
//   return new Promise((resolve) => {
//     try {
//       fetch("https://timor.tech/api/holiday/next").then((res) => {
//         res.json().then((resJ) => {
//           const {
//             holiday: { date, name, rest },
//           } = resJ;
//           resolve(
//             `还有${rest}天，我们将迎来今年的${name}，具体时间是：${date}`
//           );
//         });
//       });
//     } catch {
//       resolve(null);
//     }
//   });
// };

// Promise.all([getHoliday()]).then(([holiday]) => {
//   document.body.innerText = `
//     ${getDefaultText() /** 开场白 */}

//     ${getTodayText()}

//     【今天天气】：
//     ${getTodayWeather() /** 天气描述 */}
//     【倒计时】：
//     ${jinianriStr() /**纪念日 */}
//     【节假日】：
//     ${holiday}

//     ${getTotalDay() /** 总天数描述 */}
// `;
// });
const getHoliday = () => {
  let { jieri } = searchObj;
  if (!jieri) return "";
  jieri = JSON.parse(jieri);
  const {
    holiday: { date, name, rest },
  } = jieri;
  return `还有${rest}天，我们将迎来今年的${name}，具体时间是：${date}`;
};

document.body.innerText = `
${getDefaultText() /** 开场白 */}
  
${getTodayText()}

【温度提醒】：
${getTodayWeather() /** 天气描述 */}

【倒计时】：
${jinianriStr() /**纪念日 */}

【节假日】：
${getHoliday() || '暂无节假日信息' /**节假日 */}

${getTotalDay() /** 总天数描述 */}
`;
